package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 模拟 服务端.
 *
 * @author 宫新程
 * @since 2018/12/23 8:14 PM
 */
public class MyServer {

  private static ExecutorService pool = Executors.newFixedThreadPool(3);

  /** 模拟服务端. */
  public static void main(String[] args) throws Exception {
    // 创建 ServerSocket
    ServerSocket server = new ServerSocket(8888);
    System.out.println("服务端启动成功 ！");

    while (true) {
      // 接受客户端请求. 阻塞方法！
      Socket client = server.accept();

      // 分配给线程池去执行
      pool.execute(
          () -> {
            try {
              // 获取输入流
              InputStream inputStream = client.getInputStream();

              // 从输入流中获取数据.
              BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
              String message = br.lines().collect(Collectors.joining(System.lineSeparator()));
              System.out.println(
                  "当前线程名称："
                      + Thread.currentThread().getName()
                      + "；获取到的数据为："
                      + message
                      + "，客户端请求关闭~");

              // 返回数据
              OutputStream outputStream = client.getOutputStream();
              PrintWriter out = new PrintWriter(outputStream);
              out.print(message);
              out.flush();

              out.close();
              br.close();
              client.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          });
    }
  }
}
